package com.social.excption;


import com.social.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.DateTimeException;
import java.util.HashMap;
import java.util.Map;

import static com.social.constant.MessageConstant.DATA_VALID_FAIL;


/**
 * @author zero
 * @version 1.0
 * @project demo
 * @description 统一异常处理类
 * @date 2022/10/10 13:47:28
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException e){
        /**
            * @Author XiaoXu
            * @Date 2022/10/24
            * @Param [e]
            * @Return Result
            * @Description 数据校验异常统一处理
         */
        Map<String,String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError ->{
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return Result.fail(DATA_VALID_FAIL,map);
    }


//    @ExceptionHandler(value = RuntimeException.class)
//    public Result handler(RuntimeException e){
//        log.error("运行时异常：---------" + e.getMessage());
//        return Result.fail(400, e.getMessage());
//    }
//
//    @ExceptionHandler({Exception.class})    //申明捕获那个异常类
//    public Result ExceptionDemo(Exception e) {
//        logger.error(e.getMessage(), e);
//        return Result.fail(400,e.getMessage());
//    }

    //    @ExceptionHandler(value = RuntimeException.class)
    //    public Result handler(RuntimeException e){
    //        log.error("运行时异常：---------"+e.getMessage());
    //        return Result.fail(400, "操作异常");
    //    }
    //
    //    @ExceptionHandler({Exception.class})    //申明捕获那个异常类
    //    public Result ExceptionDemo(Exception e) {
    //        logger.error(e.getMessage(), e);
    //        return Result.fail(500,"系统异常");
    //    }

}

